package com.zhiyou.app.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageInfo;
import com.zhiyou.app.common.constant.UserHandler;
import com.zhiyou.app.common.util.IPUtil;
import com.zhiyou.app.common.vo.resp.Response;
import com.zhiyou.app.config.oss.OssUtil;
import com.zhiyou.app.pojo.bo.PayResult;
import com.zhiyou.app.pojo.bo.PrePayCrateResult;
import com.zhiyou.app.pojo.entity.OrderEntity;
import com.zhiyou.app.pojo.enums.OrderStatusEnum;
import com.zhiyou.app.pojo.vo.*;
import com.zhiyou.app.service.IOrderService;
import com.zhiyou.app.service.ITaskService;
import com.zhiyou.app.service.WechatService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author jonathan.z
 * @since 2025-07-03
 */
@Slf4j
@RestController
@RequestMapping("/order")
@Api(tags = "订单管理")
public class OrderController {
    @Resource
    private IOrderService orderService;
    @Resource
    private ITaskService taskService;
    @Resource
    private WechatService wechatService;
    @Resource
    private OssUtil ossUtil;

    @ApiOperation(value = "创建订单")
    @PostMapping("/createOrder")
    public Response<CreateOrderResponseVo> createOrder(@RequestBody OrderCreateRequestVo orderCreateRequestVo, HttpServletRequest request) {
        orderCreateRequestVo.setClientIP(IPUtil.getClientIP(request));
        orderCreateRequestVo.getIdPhotoOrderBindParam().setPhotoUrl(ossUtil.useFile(orderCreateRequestVo.getIdPhotoOrderBindParam().getPhotoUrl(), "taskFile"));
        orderCreateRequestVo.setBindParam(BeanUtil.beanToMap(orderCreateRequestVo.getIdPhotoOrderBindParam()));
        CreateOrderResponseVo createOrderResponseVo = orderService.createOrder(orderCreateRequestVo);
        return Response.successWithData(createOrderResponseVo);
    }

    @ApiOperation(value = "已有系统订单创建微信支付订单，并返回支付信息")
    @PostMapping("/preOrder4PayWithOrderNum")
    public Response<PrePayCrateResult> createWxPreOrder(@RequestBody PreOrder4PayRequestVo preOrder4PayRequestVo, HttpServletRequest request) {
        OrderEntity one = orderService.getOne(new LambdaQueryWrapper<OrderEntity>().eq(OrderEntity::getOrderNum, preOrder4PayRequestVo.getOrderNum()));
        if (one == null) {
            return Response.failed("订单不存在");
        }
        if (taskService.getOrderTaskCombineResult(preOrder4PayRequestVo.getOrderNum()).getResultMap().isEmpty()) {
            return Response.failed("订单任务未完成");
        }
        preOrder4PayRequestVo.setOrder(one);
        preOrder4PayRequestVo.setClientIP(IPUtil.getClientIP(request));
        return Response.successWithData(orderService.createPreOrder(preOrder4PayRequestVo));
    }

    @ApiOperation(value = "支付后查询支付结果，自定义等待时长，默认30s")
    @GetMapping("/getWxPayResult")
    public Response<PayResult> getWxPayResult(@RequestParam @ApiParam(name = "payKey", value = "支付key,来源预订单创建", required = true) String payKey,
                                              @RequestParam @ApiParam(name = "waitSecond", value = "支付减产最长等待时间(秒)", defaultValue = "30") int waitSecond) throws ExecutionException, InterruptedException {
        return Response.successWithData(wechatService.waitForPayResult(payKey, waitSecond).get());
    }


    @ApiOperation(value = "查询订单")
    @PostMapping("/queryOrder")
    public Response<PageInfo<OrderQueryResponseVo>> queryOrder(@RequestBody OrderQueryRequestVo orderQueryRequestVo) {
        return Response.successWithData(orderService.queryOrder(orderQueryRequestVo));
    }

    @ApiOperation(value = "查询我的订单")
    @PostMapping("/queryMyOrder")
    public Response<PageInfo<OrderQueryResponseVo>> queryMyOrder(@RequestBody OrderQueryRequestVo orderQueryRequestVo) {
        orderQueryRequestVo.setUserId(UserHandler.getLoginUser().getUserId());
        return Response.successWithData(orderService.queryOrder(orderQueryRequestVo));
    }

    @ApiOperation(value = "查询订单商品信息")
    @GetMapping("/queryOrderGoods/{orderNum}")
    public Response<List<OrderGoodsItem>> queryOrderGoods(@PathVariable String orderNum) {
        return Response.successWithData(orderService.queryOrderGoodInfoResponseVo(orderNum));
    }

    @ApiOperation(value = "订单退款")
    @PostMapping("/refundOrder")
    public Response<Boolean> refund(@RequestBody UserRefundOrderRequestVo userRefundOrderRequestVo) {
        return Response.successWithData(orderService.userRefundOrder(userRefundOrderRequestVo));
    }

    @ApiOperation(value = "后台处理退款")
    @PostMapping("/handleRefund")
    public Response<Boolean> handleRefund(@RequestBody HandleRefundRequestVo handleRefundRequestVo) {
        return Response.successWithData(orderService.handleRefund(handleRefundRequestVo));
    }

    @ApiOperation(value = "查询退款订单明细")
    @PostMapping("/queryRefundList")
    public Response<PageInfo<RefundListDetailVo>> queryRefundList(@RequestBody RefundListQueryRequestVo refundListQueryRequestVo) {
        return Response.successWithData(orderService.queryRefundList(refundListQueryRequestVo));
    }

    @ApiOperation(value = "查询订单明细")
    @GetMapping("/queryOrderDetail/{orderNum}")
    public Response<OrderQueryResponseVo> queryOrderDetail(@PathVariable String orderNum) {
        return Response.successWithData(orderService.orderDetail(orderNum));
    }

    @ApiOperation(value = "手动完成订单，如不手动执行，后台会3天后自动执行")
    @GetMapping("/completeOrder/{orderNum}")
    public Response<Boolean> completeOrder(@PathVariable String orderNum) {
        OrderEntity orderEntity = orderService.getOne(new LambdaQueryWrapper<OrderEntity>().eq(OrderEntity::getOrderNum, orderNum));
        if (orderEntity != null && orderEntity.getOrderStatus() == OrderStatusEnum.FINISHED) {
            orderService.completeOrder(orderEntity);
            return Response.successWithData(true);
        } else {
            return Response.failed("订单不存在或订单任务未完成不正确");
        }
    }


}
